package com.copd.controller;

import com.copd.common.ApiResponse;
import com.copd.dto.BackupDataQueryRequest;
import com.copd.service.BackupDataService;
import com.copd.service.DoctorOperationLogService;
import com.copd.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;

@Api(tags = "备份数据管理接口", description = "备份数据相关的接口")
@RestController
@RequestMapping("/api/backups")
public class BackupDataController {
    private static final Logger logger = LoggerFactory.getLogger(BackupDataController.class);
    
    @Autowired
    private BackupDataService backupDataService;
    
    @Autowired
    private DoctorOperationLogService logService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 从请求中获取医生ID
     */
    private void setDoctorIdFromRequest(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                Integer doctorId = jwtUtil.getUserIdFromToken(token);
                request.setAttribute("doctorId", doctorId);
            }
        } catch (Exception e) {
            logger.error("从Token获取医生ID失败", e);
        }
    }
    
    /**
     * 获取当前医生ID
     */
    private Integer getCurrentDoctorId(HttpServletRequest request) {
        Object doctorIdObj = request.getAttribute("doctorId");
        return doctorIdObj != null ? (Integer) doctorIdObj : null;
    }

    @ApiOperation(value = "查询备份数据", notes = "根据条件查询备份数据")
    @GetMapping
    public ResponseEntity<?> queryBackupData(
            @ApiParam(value = "患者ID", required = false) @RequestParam(required = false) Integer patientId,
            @ApiParam(value = "备份表名", required = false) @RequestParam(required = false) String tableName,
            @ApiParam(value = "操作类型", required = false) @RequestParam(required = false) String operationType,
            @ApiParam(value = "开始时间", required = false) @RequestParam(required = false) String startTime,
            @ApiParam(value = "结束时间", required = false) @RequestParam(required = false) String endTime,
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam(value = "每页大小", defaultValue = "10") @RequestParam(defaultValue = "10") Integer size,
            HttpServletRequest request) {
        
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(request);
            Integer doctorId = getCurrentDoctorId(request);
            
            // 构建查询请求
            BackupDataQueryRequest queryRequest = new BackupDataQueryRequest();
            queryRequest.setPatientId(patientId);
            queryRequest.setTableName(tableName);
            queryRequest.setOperationType(operationType);
            queryRequest.setStartTime(startTime);
            queryRequest.setEndTime(endTime);
            queryRequest.setPage(page);
            queryRequest.setSize(size);
            
            // 查询备份数据
            Map<String, Object> result = backupDataService.queryBackupData(queryRequest, doctorId);
            
            // 记录操作日志
            logService.logPatientOperation(
                doctorId,
                patientId,
                "查询备份",
                request.getRemoteAddr(),
                request.getHeader("User-Agent"),
                true,
                null,
                "backup_data",
                null,
                "查询备份数据，条件：" + queryRequest
            );
            
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            logger.error("查询备份数据失败", e);
            return ResponseEntity.badRequest().body(ApiResponse.error("查询备份数据失败：" + e.getMessage()));
        }
    }
    
    @ApiOperation(value = "获取备份表信息", notes = "获取系统中的备份表信息")
    @GetMapping("/tables")
    public ResponseEntity<?> getBackupTablesInfo(HttpServletRequest request) {
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(request);
            Integer doctorId = getCurrentDoctorId(request);
            
            // 获取备份表信息
            Map<String, Object> result = backupDataService.getBackupTablesInfo(doctorId);
            
            // 记录操作日志
            logService.logPatientOperation(
                doctorId,
                null,
                "查询",
                request.getRemoteAddr(),
                request.getHeader("User-Agent"),
                true,
                null,
                "backup_tables",
                null,
                "获取备份表信息"
            );
            
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            logger.error("获取备份表信息失败", e);
            return ResponseEntity.badRequest().body(ApiResponse.error("获取备份表信息失败：" + e.getMessage()));
        }
    }
    
    @ApiOperation(value = "获取备份操作日志", notes = "获取备份操作相关的日志记录")
    @GetMapping("/logs")
    public ResponseEntity<?> getBackupOperationLogs(
            @ApiParam(value = "医生ID", required = false) @RequestParam(required = false) Integer doctorId,
            @ApiParam(value = "患者ID", required = false) @RequestParam(required = false) Integer patientId,
            @ApiParam(value = "表名", required = false) @RequestParam(required = false) String tableName,
            @ApiParam(value = "操作类型", required = false) @RequestParam(required = false) String operationType,
            @ApiParam(value = "开始时间", required = false) @RequestParam(required = false) String startTime,
            @ApiParam(value = "结束时间", required = false) @RequestParam(required = false) String endTime,
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam(value = "每页大小", defaultValue = "10") @RequestParam(defaultValue = "10") Integer size,
            HttpServletRequest request) {
        
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(request);
            Integer currentDoctorId = getCurrentDoctorId(request);
            
            // 如果没有指定医生ID，则使用当前登录的医生ID
            if (doctorId == null) {
                doctorId = currentDoctorId;
            }
            
            // 获取备份操作日志
            Map<String, Object> result = backupDataService.getBackupOperationLogs(
                doctorId, patientId, tableName, operationType, startTime, endTime, page, size);
            
            // 记录操作日志
            logService.logPatientOperation(
                currentDoctorId,
                patientId,
                "查询",
                request.getRemoteAddr(),
                request.getHeader("User-Agent"),
                true,
                null,
                "backup_logs",
                null,
                "查询备份操作日志，条件：医生ID=" + doctorId + ", 患者ID=" + patientId + 
                ", 表名=" + tableName + ", 操作类型=" + operationType + 
                ", 时间范围=" + startTime + " 至 " + endTime
            );
            
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            logger.error("获取备份操作日志失败", e);
            return ResponseEntity.badRequest().body(ApiResponse.error("获取备份操作日志失败：" + e.getMessage()));
        }
    }
    
    @ApiOperation(value = "获取患者备份信息", notes = "获取特定患者的详细备份信息，包括所有备份表的数据统计和最新记录")
    @GetMapping("/patient/{patientId}/detailed")
    public ResponseEntity<?> getPatientBackupInfo(
            @ApiParam(value = "患者ID", required = true) @PathVariable Integer patientId,
            HttpServletRequest request) {
        
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(request);
            Integer doctorId = getCurrentDoctorId(request);
            
            // 获取患者详细备份信息
            Map<String, Object> detailedPatientInfo = backupDataService.getDetailedPatientBackupInfo(patientId, doctorId);
            
            // 记录操作日志
            logService.logPatientOperation(
                doctorId,
                patientId,
                "查询",
                request.getRemoteAddr(),
                request.getHeader("User-Agent"),
                true,
                null,
                "patient_info_backup",
                patientId,
                "查询患者ID为" + patientId + "的备份信息"
            );
            
            return ResponseEntity.ok(ApiResponse.success(detailedPatientInfo));
        } catch (Exception e) {
            logger.error("获取患者备份信息失败", e);
            return ResponseEntity.badRequest().body(ApiResponse.error("获取患者备份信息失败：" + e.getMessage()));
        }
    }
    
    @ApiOperation(value = "获取患者所有备份表数据", notes = "直接获取指定患者在所有备份表（患者基本信息备份表、诊断记录备份表、检查项目记录备份表、治疗项目记录备份表、出院建议记录备份表）中的原始数据")
    @GetMapping("/patient/{patientId}")
    public ResponseEntity<?> getPatientRawBackupData(
            @ApiParam(value = "患者ID", required = true) @PathVariable Integer patientId,
            HttpServletRequest request) {
        
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(request);
            Integer doctorId = getCurrentDoctorId(request);
            
            // 查询所有备份表的患者数据
            Map<String, Object> rawBackupData = backupDataService.getPatientRawBackupData(patientId);
            
            // 记录操作日志
            logService.logPatientOperation(
                doctorId,
                patientId,
                "查询",
                request.getRemoteAddr(),
                request.getHeader("User-Agent"),
                true,
                null,
                "backup_tables",
                patientId,
                "查询患者ID为" + patientId + "的所有备份表数据（患者基本信息、诊断记录、检查项目、治疗项目、出院建议）"
            );
            
            return ResponseEntity.ok(ApiResponse.success(rawBackupData));
        } catch (Exception e) {
            logger.error("获取患者备份表数据失败", e);
            return ResponseEntity.badRequest().body(ApiResponse.error("获取患者备份表数据失败：" + e.getMessage()));
        }
    }
} 